package com.video.commons.runtimelog;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;
import java.util.UUID;

/**
 * 这个aop主要在于拦截所有请求，在请求开始前生产一个请求标识，如果出现异常根据标识方便与通过日志进行异常跟踪
 */
@Aspect
//@Component
@Order(100)
@Slf4j
public class RequestAop {

    /**
     * 拦截所有的controller
     * @param joinPoint
     * @return
     */
    @Around("execution(* com.video.controller..*.*(..))")
    public Object requestAop(ProceedingJoinPoint joinPoint) throws Throwable {


        //获得目标方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RequestUnLog annotation = method.getAnnotation(RequestUnLog.class);
        if (annotation == null){
            //没注解 则开启记录表示
            RequestIdThreadLocal.putLog(true);
        }

        String id = UUID.randomUUID().toString();
        //保存请求的id
        RequestIdThreadLocal.putId(id);
        Object result = null;
        //异常变量
        try {
            //调用目标方法
            result = joinPoint.proceed();
        } catch (Throwable t) {
            //将运行日志信息保存到日志存储栈中
            RunLogUtil.error("全局异常处理！！", t);
            //继续向上抛
            throw t;
        } finally {
            //请求结束后，清除id
            RequestIdThreadLocal.clear();
        }

        return result;
    }
}
